/*
  Copyright (c) 2009, Pablo Davi Faria da Silva
  Novesfora.com.br
  Blog.des84.com
  All rights reserved.

  Redistribution and use in source and binary forms, with or without 
  modification, are permitted provided that the following conditions are
  met:

  * Redistributions of source code must retain the above copyright notice, 
    this list of conditions and the following disclaimer.
  
  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the 
    documentation and/or other materials provided with the distribution.
  
  * Neither the name of Novesfora, DES84 nor the names of its 
    contributors may be used to endorse or promote products derived from 
    this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package Born.loader
{	
	import Born.events.Events;
	import Born.utils.Numbers.NumberUtils;
	
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;

	public class LoadFile extends MovieClip
	{
		private var $loaditLoader			:Loader;
		private var $loaditRequest			:URLRequest;
		private var _targetIt				:String;
		private var _smooth					:Boolean;
		private var $debug					:Boolean;
		
		public var LoadFilePercent			:uint;
		public var id						:uint;
		
		public function LoadFile(targetIt:String, smooth:Boolean = false, preventCache:Boolean = false, debug:Boolean = false ):void
		{
			var cacheString:String = "";
			if ( preventCache ) cacheString = String("?cacheControl=" + NumberUtils.Random(0,1000));
			_targetIt = String(targetIt + cacheString);
			_smooth = smooth;
			$debug = debug;
			
			$loaditLoader 	= new Loader();
			$loaditRequest 	= new URLRequest(_targetIt);
			
			$loaditLoader.load($loaditRequest);
			$loaditLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaditComplete);
			$loaditLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loaditProgress);
			$loaditLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loaditError);
			$loaditLoader.contentLoaderInfo.addEventListener(Event.UNLOAD, loaditDoNothing);
			$loaditLoader.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, loaditDoNothing);
			$loaditLoader.contentLoaderInfo.addEventListener(Event.DEACTIVATE, loaditDoNothing);
			
			super.addEventListener(Event.ADDED_TO_STAGE, addedClass);
			super.addEventListener(Event.REMOVED_FROM_STAGE, removeClass);
			
			if ( $debug ) trace("LoadFile > _targetIt: " + _targetIt);
		}
		
		private function loaditDoNothing(e:*):void
		{
			// Do nothing
		}
		/**
		 * Return the to listener the progress data 
		 * @param p
		 */		
		private function loaditProgress(p:ProgressEvent):void
		{
			LoadFilePercent = Math.ceil( ( p.bytesLoaded / p.bytesTotal ) * 100 );
			dispatchEvent(new Events(Events.PROGRESS, 
				{ 
					PercentLoaded:LoadFilePercent,
					TotalBytes: int(( p.bytesTotal )/1024),
					LoadedBytes: p.bytesLoaded
				}
			));
			
			if ( $debug ) trace("LoadFile > LoadFilePercent: " + LoadFilePercent);
		}
		/**
		 * Image loaded. Load complete function 
		 * @param e
		 */		
		private function loaditComplete(e:Event):void
		{
			if ( _smooth ) ( e.currentTarget.content as Bitmap ).smoothing = true;
			dispatchEvent(new Events(Events.COMPLETE, { LoadFile : this }));
			
			if ( $debug ) trace("LoadFile > loaditComplete: OK");
		}
		/**
		 * On load error, file address error 
		 * @param e
		 */		
		private function loaditError(e:IOErrorEvent):void
		{
			dispatchEvent(new Events(Events.IOError, { Error:e.text } ));
		}
		/**
		 * Remove all the listeners on unload file
		 */		
		public function unload():void
		{
			removeClass(null);
		}
		/**
		 * Adicionar o loader somente depois que a classe for adicionada
		 * assim evita animacoes rodarem durante o carregamento do arquivo 
		 * @param e
		 */		
		private function addedClass(e:Event):void
		{
			super.addChild($loaditLoader);
		}
		/**
		 * Remove all the listeners on class removed
		 */	
		private function removeClass(e:Event):void
		{
			$loaditLoader.unload();
			$loaditLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, 			loaditComplete);
			$loaditLoader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, 	loaditProgress);
			$loaditLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, 	loaditError);
		}
	}
}